package com.brozha.ans_sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.brozha.ans_sys.entity.News;
import com.brozha.ans_sys.mapper.NewsMapper;
import com.brozha.ans_sys.service.NewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brozha.ans_sys.utils.HttpUtils;
import com.brozha.ans_sys.utils.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author brozha
 * @since 2021-04-04
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {

    private static final String BASE_URL_HEAD1 = "http://ex.cssn.cn/zgs/zgs_zgjds";
    private static final String FIRST_URL1 = "http://ex.cssn.cn/zgs/zgs_zgjds/index.shtml";

    /**
     * 获取第一页的内容
     * @return
     */
    @Override
    public List<News> crawlerTask1() {
        HttpUtils httpUtils = new HttpUtils();
        String url = FIRST_URL1;
        String html = httpUtils.doGetHtml(url);
        Document doc = Jsoup.parse(html);
        Elements elements = doc.select(".ImageListView a");
        List<News> res = new ArrayList<>();
        for (Element element : elements) {
            String newsUrl = BASE_URL_HEAD1+element.attr("href").substring(1);
            String newsTitle = element.text();
            News news = new News();
            news.setNewsUrl(newsUrl);
            news.setNewsTitle(newsTitle);
            res.add(news);
        }
        return res;
    }

    /**
     * 随机返回十条新闻
     * @return
     */
    @Override
    public Result queryByRand() {
        QueryWrapper<News> qw = new QueryWrapper();
        qw.last("order by rand() limit 10");
        List<News> newsList = this.list(qw);
        return Result.success("随机查找成功！！！",newsList);
    }

    /**
     * 分页查询
     * @param curPage
     * @param size
     * @return
     */
    @Override
    public Result queryByPage(int curPage, int size) {
        Page<News> pNews = new Page<>(curPage,size);
        QueryWrapper<News> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        Page<News> newsPage = this.page(pNews, qw);
        Map map = new HashMap();
        long total = newsPage.getTotal();
        List<News> news = newsPage.getRecords();
        map.put("total",total);
        map.put("newsList",news);

        return Result.success("查询成功！！！",map);
    }
}
